package leetcode.median;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * ClassName: $15_ThreeSum
 * Description:
 * date: 2022-01-10 21:03
 *
 * @author liyifan
 */
public class $15_ThreeSum {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();

        Arrays.sort(nums);
        int len = nums.length;
        for(int i = 0;i < len;i++) {
            if (nums[i] > 0) {
                return res;
            }

            if (i > 0 && nums[i] == nums[i - 1])
                continue;

            int first = nums[i];
            int left = i + 1;
            int right = len - 1;
            while (left < right) {
                int temp = first + nums[left] + nums[right];

                if (temp == 0){
                    List<Integer> tmpList = new LinkedList<>();
                    tmpList.add(first);
                    tmpList.add(nums[left]);
                    tmpList.add(nums[right]);
                    res.add(tmpList);

                    // 移动left和right 寻找下一个答案
                    while (left < right && nums[left + 1] == nums[left])
                        left++;
                    while (left < right && nums[right - 1] == nums[right])
                        right--;

                    left++;
                    right--;
                } else if (temp < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }

    public List<List<Integer>> threeSum2(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        int len = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if (nums[i] > 0) {
                return res;
            }
            if (i > 0 && nums[i] == nums[i - 1])
                continue;

            int first = nums[i];
            int left = i + 1;
            int right = left - 1;
            while (left < right) {
                int temp = first + nums[left] + nums[right];
                if (temp > 0) {
                    right--;
                } else if (temp < 0) {
                    left++;
                } else {
                    List<Integer> tempList = new LinkedList<>();
                    tempList.add(first);
                    tempList.add(nums[left]);
                    tempList.add(nums[right]);
                    res.add(tempList);

                    while (left < right && nums[left] == nums[left + 1])
                        left++;
                    while (left < right && nums[right] == nums[right - 1])
                        right--;

                    left++;
                    right--;
                }
            }
        }
        return res;
    }

}
